package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentArticleDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentArticleMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentArticleServiceImpl implements ContentArticleService {

    @Resource
    private ContentArticleMapper contentArticleMapper;

    @Override
    public Long createArticle(ContentArticleSaveReqVO createReqVO) {
        ContentArticleDO article = BeanUtils.toBean(createReqVO, ContentArticleDO.class);
        contentArticleMapper.insert(article);
        return article.getId();
    }

    @Override
    public void updateArticle(ContentArticleSaveReqVO updateReqVO) {
        validateArticleExists(updateReqVO.getId());
        ContentArticleDO updateObj = BeanUtils.toBean(updateReqVO, ContentArticleDO.class);
        contentArticleMapper.updateById(updateObj);
    }

    @Override
    public void deleteArticle(Long id) {
        validateArticleExists(id);
        contentArticleMapper.deleteById(id);
    }

    private void validateArticleExists(Long id) {
        if (contentArticleMapper.selectById(id) == null) {
            throw exception(ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public ContentArticleDO getArticle(Long id) {
        return contentArticleMapper.selectById(id);
    }

    @Override
    public PageResult<ContentArticleDO> getArticlePage(ContentArticlePageReqVO pageReqVO) {
        return contentArticleMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteArticleListByIds(List<Long> ids) {
        ids.forEach(this::validateArticleExists);
        contentArticleMapper.deleteBatchIds(ids);
    }

}
